// opencv async detector demo
// Author: lihaoweicv@hotmail.com
// MIT License 

#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include "base/macro.h"
#include "runner/async_runner.h"
#include "detector/demo_detector.h"

int main()
{
    // 异步runner
    cvf::Async_Preview_Runner runner;
    // 绑定检测器
    std::shared_ptr<cvf::Abstract_Detector> detector = std::make_shared<cvf::Demo_Detector>();;
    runner.bind_detector(detector);
    // 可设置运行的最大fps 调和CPU负载
    // 也可以增加接口去绑定runner到固定的CPU核心
    // runner.set_max_fps(5);
    runner.set_max_fps(100);

    // 初始化模型
    cvf::Status status;
    std::vector<std::string> modelPaths;
    status = runner.init_models(modelPaths);
    if(status != cvf::Status_OK)
    {
        LOGI("init model failed!\n");
        return -1;
    }
    // 开启loop线程
    runner.start();

    // 主线程做其他事情
    // 这里做preview 和简单的交互
    cv::VideoCapture cap(0);
    if(!cap.isOpened())
    {
        LOGI("open cam failed!\n");
        return -1;
    }
    cv::namedWindow("preview",0);
    while (1)
    {
        cv::Mat frame;
        cap >> frame;
        cvf::DetInfo detInfo;
        if (frame.data)
        {
            runner.push_frame(frame);
            std::this_thread::sleep_for(std::chrono::microseconds(50));
            //异步的结果
            runner.fetch_dets(detInfo);
            if(detInfo.hasObject)
            {
                cv::rectangle(frame, detInfo.detBox, cv::Scalar(0,0,255),3,16);
            }
            cv::imshow("preview", frame);
            char key = cv::waitKey(10);
            if(key == 27)
                break;
            //对关键帧/ 静态图片进行阻塞式不丢失检测
            if(key == 'k')
            {
                cvf::Runner_Sub_Detect_Job job;
                job.imgBGR = frame.clone();
                runner.submit_once_sub_detect_job(&job);
                cvf::DetInfo det;
                job.wait_and_get_dets(det);

            }

        }
    }
    // 停止runner
    runner.stop();
    return 0;
}
